﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Text;

namespace blackenter.Data {
    public abstract class DbFactory {

        #region Fields

        delegate T ObjectActivator<out T>();

        private static ObjectActivator<ISiteDbContext> _createSiteDbContext;
        private static ObjectActivator<IPageDbContext> _createPageDbContext;

        #endregion

        #region Methods

        public static void SetSiteDbContext(Type typeOfDbContext) {
            _createSiteDbContext = CompileActivator<ISiteDbContext>(typeOfDbContext);
        }

        public static void SetPageDbContext(Type typeOfDbContext) {
            _createPageDbContext = CompileActivator<IPageDbContext>(typeOfDbContext);
        }

        public static ISiteDbContext GetSiteDbContext() {
            return _createSiteDbContext();
        }

        public static IPageDbContext GetPageDbContext() {
            return _createPageDbContext();
        }

        private static ObjectActivator<T> CompileActivator<T>(Type objectType) {
            ConstructorInfo ctor = objectType.GetConstructor(new Type[0]); // parameterless constructor
            NewExpression lbaNew = Expression.New(objectType);
            LambdaExpression lbaNewWrap = Expression.Lambda(typeof(ObjectActivator<T>), lbaNew);
            return (ObjectActivator<T>)lbaNewWrap.Compile();
        }

        #endregion

    }
}
